﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using WebApiV2.Data;
using WebApiV2.Data.Entity;

namespace WebApiV2.Domain
{
    public class EfResponsitory<T> : IRespository<T> where T : BaseEntity
    {
        private readonly Admain3200DbContext db;



        private DbSet<T> _entity;

        private DbSet<T> Entity
        {
            get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }
        }


        public EfResponsitory(Admain3200DbContext admain3200DbContext)
        {
            db = admain3200DbContext;
        }

        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }

        public void Delete(T entity)
        {
            Entity.Remove(entity);
            db.SaveChanges();
        }

        public void Delete(int id)
        {
            var row = Table.Where(x => x.Id == id).FirstOrDefault();

            //调用上面的函数
            Delete(row);
        }

        public T GetById(int id)
        {
            return _entity.Where(x => x.Id == id).FirstOrDefault();

        }

        public void Insert(T entity)
        {
            Entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            Entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            Entity.Update(entity);
            db.SaveChanges();
        }


       

        public void Delete(IEnumerable<T> entites)
        {
            Entity.RemoveRange(entites);
            db.SaveChanges();
        }

    }
}
